package com.gulimall.order.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Configuration
public class RabbitMQConfig {
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 定制RabbitTemplate
     */
    @PostConstruct
    public void  initRabbitTemplate(){
        // 设置消息抵达消息代理的回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback(){
            /**
             * @param correlationData   消息的唯一id
             * @param ack  只要消息抵达消息代理，就ack == true,不管消息有没有被确认
             * @param cause
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("confirm...correlationData["+ correlationData+"] === >ack["+ack+"] ===> cause["+cause+ "]");
            }
        });
        //设置消息抵达队列的失败回调
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback(){
            /**
             * 只要消息没有投递给指定的队列，就触发这个失败回调
             * @param returnedMessage  ReturnedMessage包含以下数据
             *     private final Message message;  投递失败的消息详细信息
             *     private final int replyCode;    回复的状态码
             *     private final String replyText; 回复的文本内容
             *     private final String exchange;  当时这个消息发给哪个交换机
             *     private final String routingKey; 当时这个消息用哪个路由键
             */
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("message = " + returnedMessage.getMessage() +
                        " replyCode = " + returnedMessage.getReplyCode() + "replyText = " + returnedMessage.getReplyText()
                        + " exchange = " + returnedMessage.getExchange() + "routingKey = " + returnedMessage.getRoutingKey());
            }
        });
    }
}
